1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use super::*;

/// Shift a term up or down by an amount
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Shift<T> {
    /// The amount to shift variables by
    pub shift: i32,
    /// The base of this context: leaves variables under this untouched (but not necessarily their annotations!)
    pub base: u32,
    /// The underlying typing context of this shift
    ctx: T,
}

impl<T: TyCtxMut> Shift<T> {
    /// Create a new shift
    #[inline]
    pub fn new(shift: i32, base: u32, ctx: T) -> Shift<T> {
        Shift { shift, base, ctx }
    }
}

impl<T: TyCtxMut> SubstCtx for Shift<T> {
    type Ctx = T;

    #[inline]
    fn subst_var(&mut self, ix: u32, annot: Option<&TermId>) -> Result<Option<TermId>, Error> {
        if self.shift == 0 {
            return Ok(None);
        }
        let new_ix = if ix >= self.base {
            let shifted = if self.shift < 0 {
                ix.checked_sub(-self.shift as u32)
                    .ok_or(Error::ParameterUnderflow)?
            } else {
                ix.checked_add(self.shift as u32)
                    .ok_or(Error::ParameterOverflow)?
            };
            if shifted < self.base {
                return Err(Error::HasDependency);
            };
            shifted
        } else {
            ix
        };
        let new_annot = annot.subst_rec(self)?;
        if new_ix == ix && new_annot.is_none() {
            return Ok(None);
        }
        let var = Var::new_unchecked(
            new_ix,
            new_annot.unwrap_or_else(|| annot.consed(self.ctx.cons_ctx())),
        )
        .into_id_with(self.ctx.cons_ctx());
        Ok(Some(var))
    }

    #[inline]
    fn push_param(&mut self, param_ty: Option<&TermId>) -> Result<Option<TermId>, Error> {
        let subst = if let Some(param_ty) = param_ty {
            param_ty.subst_id(self)?
        } else {
            None
        };
        self.base = self.base.checked_add(1).ok_or(Error::ParameterOverflow)?;
        Ok(subst)
    }

    #[inline]
    fn intersects(&self, filter: VarFilter, _code: Code, _form: Form) -> bool {
        self.shift != 0 && filter.fvb() >= self.base
    }

    #[inline]
    fn ctx(&mut self) -> &mut Self::Ctx {
        &mut self.ctx
    }

    #[inline]
    fn pop_param(&mut self) -> Result<(), Error> {
        self.base = self.base.checked_sub(1).ok_or(Error::ParameterUnderflow)?;
        Ok(())
    }

    #[inline]
    fn is_var_null(&self) -> bool {
        true
    }
}